package com.mask.sca.gateway.filter;

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Component
public class TraceIdFilter implements GlobalFilter, Ordered {
    private static final String TRACE_ID_HEADER = "X-Trace-Id";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = exchange.getRequest().getHeaders().getFirst(TRACE_ID_HEADER);
        ServerWebExchange targetExchange;
        if (!StringUtils.hasText(traceId)) {
            final String newTraceId = UUID.randomUUID().toString().replace("-", "");
            targetExchange = exchange.mutate()
                    .request(builder -> builder.header(TRACE_ID_HEADER, newTraceId))
                    .build();
            System.out.println("当前 traceId: " + (traceId != null ? traceId : newTraceId));
        } else {
            targetExchange = exchange;
        }
        // 继续后续过滤器链
        return chain.filter(targetExchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
} 